package com.zhongxi.guoyuan.view.beautifulStore;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.beautifulStore.BeautifulStoreAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.beautifulStore.BeautifulStoreData;
import com.zhongxi.guoyuan.entity.beautifulStore.BeautifulStoreResult;
import com.zhongxi.guoyuan.entity.beautifulStore.ServiceInfoResult;
import com.zhongxi.guoyuan.entity.subscribe.SubscribeResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.DeviceUtils;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.view.user.LoginActivity;
import com.zhongxi.guoyuan.widget.sliding.NoScrollListView;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SubscribeActivity extends BaseActivity implements View.OnClickListener, MyScrollView.OnScrollListener {

    private NoScrollListView lvList;
    private BeautifulStoreAdapter adapter;
    private TextView tvOrder;
    private Map<String, String> map = new HashMap<String, String>();
    private String id;
    private String type;
    private TextView tvTime;
    private TextView tvOriginPrice;
    private TextView tvView;
    private ImageView ivImg;
    private TextView tvProjectName;
    private TextView tvCash;
    private TextView workmanship;
    private BeautifulStoreResult result;
    private List<BeautifulStoreData> data = new ArrayList<>();
    private String status = "1";
    private LinearLayout scrollBody;
    private RelativeLayout relaLayout;
    private LinearLayout linearBegin;
    private LinearLayout linearStop;
    private MyScrollView myScrollView;
    private boolean isMeasured;
    private int scrollHeight;
    private boolean isClickShop = false;
    private RelativeLayout title;
    private RelativeLayout rl_content;
    private ImageView iv_service;
    private ImageView iv_unread_dot;
    private ProgressDialog mDialog;
    private PopupWindow pw;
    private int count;
    private ServiceInfoResult.ServiceData serviceData;
    public static final int requestFulsh = 500;
    public static final int requestFulshConver = 600;

    public static final int RESULT_CODE = 300;
    private TextView recently;
    private TextView topScore;
    private TextView great;
    private SubscribeResult subscribeResult;
    private TextView tvSub;
    private TextView tvAdd;
    private EditText etNum;
    private String orderNum = "1";

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_subscribe);
        title = (RelativeLayout) findViewById(R.id.title);
        initTitle();
        tvTitle.setText("美容预约");
        rl_content = (RelativeLayout) findViewById(R.id.rl_content);
        rl_content.setVisibility(View.GONE);
        iv_service = (ImageView) findViewById(R.id.iv_service);
        iv_unread_dot = (ImageView) findViewById(R.id.iv_dot);

        id = getIntent().getStringExtra("id");
        //实现上拉布局悬停
        initScrollPause();
        ivImg = (ImageView) findViewById(R.id.ivImg);
        tvProjectName = (TextView) findViewById(R.id.tvProjectName);
        tvCash = (TextView) findViewById(R.id.tvCash);
        tvView = (TextView) findViewById(R.id.tvView);
        tvOriginPrice = (TextView) findViewById(R.id.tvOriginPrice);
        tvTime = (TextView) findViewById(R.id.tvTime);
        workmanship = (TextView) findViewById(R.id.workmanship);
        tvOrder = (TextView) findViewById(R.id.tvOrder);

        recently = (TextView) findViewById(R.id.subscribe_text_recently);
        topScore = (TextView) findViewById(R.id.subscribe_text_topScore);
        great = (TextView) findViewById(R.id.subscribe_text_great);

        lvList = (NoScrollListView) findViewById(R.id.lvList);
        tvSub = (TextView) findViewById(R.id.tvSub);
        tvAdd = (TextView) findViewById(R.id.tvAdd);
        etNum = (EditText) findViewById(R.id.etNum);
    }

    /**
     * 上拉悬停
     */
    private void initScrollPause() {
        //滑动置顶
        scrollBody = (LinearLayout) findViewById(R.id.scrollBody);
        linearBegin = (LinearLayout) findViewById(R.id.linearBegin);
        linearStop = (LinearLayout) findViewById(R.id.linearStop);
        myScrollView = (MyScrollView) findViewById(R.id.myScrollView);

        relaLayout = (RelativeLayout) findViewById(R.id.relaLayout);
        ViewTreeObserver observer = relaLayout.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!isMeasured) {
                    scrollHeight = relaLayout.getMeasuredHeight();
                    isMeasured = true;
                }
                return true;
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new BeautifulStoreAdapter(context, data);
        lvList.setAdapter(adapter);
        type = "serviceInfo";
        String str = "&sid=" + id;
        getServer(Url.SERVICE, null, str, false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        tvOrder.setOnClickListener(this);
        myScrollView.setOnScrollListener(this);
        recently.setOnClickListener(this);
        topScore.setOnClickListener(this);
        great.setOnClickListener(this);
        tvSub.setOnClickListener(this);
        tvAdd.setOnClickListener(this);

        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (adapter.getTemp() == id) {
                    adapter.setTemp(-1);
                } else {
                    adapter.setTemp(position);
                }
                adapter.notifyDataSetChanged();
            }
        });
        rl_content.setOnClickListener(this);
    }

    @Override
    protected void processSuccessResult(String response) throws JSONException {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("serviceInfo".equals(type)) {
                ServiceInfoResult serviceInfoResult = gson.fromJson(response, ServiceInfoResult.class);
                if (null != serviceInfoResult.getSafeobj() && !"".equals(serviceInfoResult.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(serviceInfoResult.getSafeobj());
                }
                if (null != serviceInfoResult.getData() && !"".equals(serviceInfoResult.getData())) {
                    serviceData = serviceInfoResult.getData();
                    initInfo();
                }
                getStore();
            } else if ("shoplist".equals(type)) {
                result = gson.fromJson(response, BeautifulStoreResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj()))
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                if (pageNum == 1) {
                    data.clear();
                }
                if (null != result.getData() && !"".equals(result.getData())) {
                    data.addAll(result.getData());
                } else {
                    return;
                }
                adapter = new BeautifulStoreAdapter(context, data);
                lvList.setAdapter(adapter);
            } else if ("addsubscribe".equals(type)) {
                subscribeResult = gson.fromJson(response, SubscribeResult.class);
                if (null != subscribeResult.getSafeobj() && !"".equals(subscribeResult.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(subscribeResult.getSafeobj());
                }
                String mInnerCurrency = MyApplication.getInstance().getInnerCurrency();
                String mInnerprice = serviceData.getInnerprice();
                if (DataUtil.moreThanOther(mInnerCurrency, DataUtil.multiplys(mInnerprice, orderNum,2))) {
                    Intent intent = new Intent(context, OrderActivity.class);
                    Bundle builder = new Bundle();
                    builder.putString("orderNum", orderNum);
                    builder.putStringArrayList("orderidList", subscribeResult.getOrderid());
                    builder.putSerializable("shopInfo", data.get(adapter.getTemp()));
                    builder.putSerializable("goodInfo", serviceData);
                    intent.putExtra("orderidInfo", builder);
                    startActivity(intent);
                } else {
                    showMeidouNoBalance();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse res = gson.fromJson(response, BaseResponse.class);
            if (null != res.getSafeobj() && !"".equals(res.getSafeobj())) {
                MyApplication.getInstance().setSpValue(res.getSafeobj());
            }
            if (res.getCode() == 1001) {
                showShortToast("用户未登录，请先登录");
            } else if (res.getCode() == 5001) {
                showMeidouNoBalance();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 美豆余额不足
     */
    private void showMeidouNoBalance() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_pay, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView tvSurePay = (TextView) layout.findViewById(R.id.tvSurePay);
        TextView tvGouwu = (TextView) layout.findViewById(R.id.tvGouwu);
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        //放弃支付
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvSurePay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvGouwu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                setResult(RESULT_CODE);
                finish();

            }
        });
    }

    private void getStore() {
        type = "shoplist";
        String str = "&page=" + pageNum + "&lng=" + MyApplication.getInstance().getLongitude() +
                "&lat=" + MyApplication.getInstance().getLatitude() + "&orderby=" + status + "&sid=" + id;
        getServer(Url.SHOP_LIST, null, str, false, null, "get");
    }

    /**
     * 初始化服务信息
     */
    private void initInfo() {
        if (serviceData.getThumbnail() != null && !"".equals(serviceData.getThumbnail())) {
            if (serviceData.getThumbnail().endsWith(".png")) {
                Glide.with(context).load(Url.IMG_URL + serviceData.getThumbnail()).placeholder(R.mipmap.iv_eg).into(ivImg);
            } else if (serviceData.getImages() != null && serviceData.getImages().size() > 0) {
                Glide.with(context).load(Url.IMG_URL + serviceData.getImages().get(0)).placeholder(R.mipmap.iv_eg).into(ivImg);
            }
        } else if (serviceData.getImages() != null && serviceData.getImages().size() > 0) {
            Glide.with(context).load(Url.IMG_URL + serviceData.getImages().get(0)).placeholder(R.mipmap.iv_eg).into(ivImg);
        }
        if (null != serviceData.getName() && !"".equals(serviceData.getName())) {
            tvProjectName.setText(serviceData.getName());
        } else {
            tvProjectName.setText("");
        }
        if (null != serviceData.getInnerprice() && !"".equals(serviceData.getInnerprice())) {
            tvCash.setText(serviceData.getInnerprice() + " 美豆");
        } else {
            tvCash.setText("");
        }

        if (null != serviceData.getRedbeanprice() && !"".equals(serviceData.getRedbeanprice())) {
            workmanship.setText("+" + serviceData.getRedbeanprice() + " 红豆");
        } else {
            workmanship.setText("");
        }
        if (null != serviceData.getServicetime() && !"".equals(serviceData.getServicetime())) {
            tvTime.setText(serviceData.getServicetime() + " 分钟");
        } else {
            tvTime.setText("");
        }
        if (null != serviceData.getViewnum() && !"".equals(serviceData.getViewnum())) {
            tvView.setText(serviceData.getViewnum());
        } else {
            tvView.setText("0");
        }
        if (null != serviceData.getMarketprice() && !"".equals(serviceData.getMarketprice())) {
            tvOriginPrice.setText("市场价: " + serviceData.getMarketprice() + " 元");
            tvOriginPrice.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        } else {
            tvOriginPrice.setText("市场价: 0 元");
            tvOriginPrice.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvSub:
                orderNum = etNum.getText().toString().trim();
                if (DataUtil.moreThanOtherNoEqual(orderNum, "1")) {
                    orderNum = DataUtil.subtract(orderNum, "1");
                } else {
                    showShortToast("预约次数不能低于一次");
                }
                etNum.setText(orderNum);
                break;
            case R.id.tvAdd:
                orderNum = etNum.getText().toString().trim();
                if (DataUtil.moreThanOther(orderNum, "4")) {
                    ToastUtil.show(getString(R.string.limit_order));
                }else {
                    orderNum = DataUtil.add(orderNum, "1");
                    etNum.setText(orderNum);
                }
                break;
            case R.id.tvOrder:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    if (adapter.getTemp() == -1) {
                        showShortToast("请选择您所喜欢的美容院");
                    } else {
                        getData();
                    }
                } else {
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.putExtra("position", 1);
                    startActivityForResult(intent, 102);
                }
                break;
            case R.id.subscribe_text_recently:
                recently.setTextColor(getResources().getColor(R.color.title_red));
                topScore.setTextColor(getResources().getColor(R.color.gohere));
                great.setTextColor(getResources().getColor(R.color.gohere));
                pageNum = 1;
                status = "1";
                getStore();
                break;
            case R.id.subscribe_text_topScore:
                recently.setTextColor(getResources().getColor(R.color.gohere));
                topScore.setTextColor(getResources().getColor(R.color.title_red));
                great.setTextColor(getResources().getColor(R.color.gohere));
                pageNum = 1;
                status = "2";
                getStore();
                break;
            case R.id.subscribe_text_great:
                recently.setTextColor(getResources().getColor(R.color.gohere));
                topScore.setTextColor(getResources().getColor(R.color.gohere));
                great.setTextColor(getResources().getColor(R.color.title_red));
                pageNum = 1;
                status = "3";
                getStore();
                break;
            case R.id.rl_content:
                if (CommonTool.checkApkExist(SubscribeActivity.this,"com.tencent.mobileqq")){
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                            "mqqwpa://im/chat?chat_type=wpa&uin="+ Constants.QQ_NUM+"&version=1")));
                }else {
                    showShortToast("未安装QQ");
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 添加预约
     *
     * @param
     */
    private void getData() {
        type = "addsubscribe";
        Map<String, String> map = new HashMap<>();
        map.put("sid", serviceData.getId());
        map.put("shopid", data.get(adapter.getTemp()).getId());
        map.put("itemnum", orderNum);
        getServer(Url.ADD_SUBSCRIBE, map, "", false, null, "post");
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= scrollHeight) {
            if (scrollBody.getParent() != linearStop) {
                linearBegin.removeView(scrollBody);
                linearBegin.setLayoutParams(new LinearLayout.LayoutParams(scrollBody.getMeasuredWidth(), scrollBody.getMeasuredHeight()));
                linearStop.addView(scrollBody);
            }
        } else {
            if (scrollBody.getParent() != linearBegin) {
                linearStop.removeView(scrollBody);
                linearBegin.addView(scrollBody);
            }
        }
    }

    @Override
    public void scrollBottom() {
        if (!MyTextUtils.isFastDoubleClick()) {
            pageNum++;
            getStore();
        }
        if (isClickShop) {
            pageNum++;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == requestFulsh) {
            pw.dismiss();
        } else if (requestCode == requestFulshConver) {
            pw.dismiss();
        }
    }
}
